package cloud.ben.smallscalepigfarmmanagementsystem.filter;

import cloud.ben.smallscalepigfarmmanagementsystem.entity.AuthUser;
import cloud.ben.smallscalepigfarmmanagementsystem.utils.JsonUtils;
import cloud.ben.smallscalepigfarmmanagementsystem.utils.JwtTokenUtils;
import cloud.ben.smallscalepigfarmmanagementsystem.utils.RespBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Ben
 * @Date: 2022/3/2 19:14
 */
public class LoginFilter extends UsernamePasswordAuthenticationFilter {


    private static final Logger logger = LoggerFactory.getLogger(LoginFilter.class);


    private final ThreadLocal<Integer> rememberMe = new ThreadLocal<>();

    private final AuthenticationManager authenticationManager;

    private StringRedisTemplate stringRedisTemplate;

    public LoginFilter(AuthenticationManager authenticationManager,StringRedisTemplate stringRedisTemplate) {
        this.authenticationManager = authenticationManager;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public LoginFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
        super.setFilterProcessesUrl("/login");
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {
        if (!"POST".equals(request.getMethod())) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }

        // 前端传过来的是json数据
//        try {
//            AuthUser authUser = new ObjectMapper().readValue(request.getInputStream(), AuthUser.class);
//            rememberMe.set(authUser.getRememberMe() == null ? 0 : authUser.getRememberMe());
//            return authenticationManager.authenticate(
//                    new UsernamePasswordAuthenticationToken(authUser.getUsername(), authUser.getPassword(), new ArrayList<>())
//            );
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        } finally {
            // 前端传过来的是key-value数据
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            AuthUser authUser = new AuthUser(username, password);
//            rememberMe.set(authUser.getRememberMe() == null ? 0 : authUser.getRememberMe());
            return authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(authUser.getUsername(), authUser.getPassword(), new ArrayList<>()));
        }
//    }

    // 成功验证后调用的方法
    // 如果验证成功，就生成token并返回
    @Override
    protected void successfulAuthentication(HttpServletRequest request,
                                            HttpServletResponse response,
                                            FilterChain chain,
                                            Authentication authResult) throws IOException, ServletException {

        AuthUser authUser = (AuthUser) authResult.getPrincipal();
//        logger.info("authUser:" + authUser.toString());
//        boolean isRemember = rememberMe.get() == 1;

        String role = "";
        Collection<? extends GrantedAuthority> authorities = authUser.getAuthorities();
        for (GrantedAuthority authority : authorities){
            role = authority.getAuthority();
        }
        String token = JwtTokenUtils.createToken(authUser.getUsername(), role);
        //String token = JwtTokenUtils.createToken(jwtUser.getUsername(), false);
        // 返回创建成功的token
        // 但是这里创建的token只是单纯的token
        // 按照jwt的规定，最后请求的时候应该是 `Bearer token`
        logger.info("------------------->"+request.getParameter("username"));
        stringRedisTemplate.opsForValue().set(JwtTokenUtils.TOKEN_PREFIX+token,request.getParameter("username"),60*10, TimeUnit.SECONDS);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(HttpStatus.OK.value());
        HashMap<String,String> hashMap=new HashMap<>();
        hashMap.put("token", token);
        response.getWriter().write(JsonUtils.toString(RespBean.ok(hashMap)));
//        response.setHeader("token", JwtTokenUtils.TOKEN_PREFIX + token);
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        response.getWriter().write("authentication failed, reason: " + failed.getMessage());
    }
}
